﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using ERP_SaaS_WinForm.采购管理.Sup;

namespace ERP_SaaS_WinForm.采购管理
{
    public partial class SupAdd : Form
    {
        public SupAdd()
        {
            InitializeComponent();
            
            // 设置窗体标题
            this.Text = "添加物料信息";
            
            // 设置窗体大小
            this.Size = new Size(600, 500);
            
            // 设置窗体居中显示
            this.StartPosition = FormStartPosition.CenterParent;
            
            Console.WriteLine("SupAdd窗体已初始化");
        }
        
        /// <summary>
        /// 窗体加载事件
        /// </summary>
        private void SupAdd_Load(object sender, EventArgs e)
        {
            Console.WriteLine("SupAdd窗体加载完成");
        }
        
        /// <summary>
        /// 添加供应商按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void butAddSup_Click(object sender, EventArgs e)
        {
            try
            {
                Console.WriteLine("添加供应商按钮被点击");
                
                // 数据验证
                if (string.IsNullOrWhiteSpace(txtsupCode?.Text?.Trim()))
                {
                    MessageBox.Show("请输入供应商编号！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtsupCode?.Focus();
                    return;
                }
                
                if (string.IsNullOrWhiteSpace(txtsupName?.Text?.Trim()))
                {
                    MessageBox.Show("请输入供应商名称！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtsupName?.Focus();
                    return;
                }
                
                // 创建供应商数据对象
                var supplierData = new AddSupSot
                {
                    SupCode = txtsupCode?.Text?.Trim() ?? "",
                    SupName = txtsupName?.Text?.Trim() ?? "",
                    SupGradeId = 1,
                    SupPhoneName = txtsupPhoneName?.Text?.Trim() ?? "",
                    SupState = 1, // 默认启用状态
                    SupPhone = txtsupPhone?.Text?.Trim() ?? "",
                    SupRemark = txtsupRemark?.Text?.Trim() ?? ""
                };
                
                Console.WriteLine($"准备发送供应商数据: {JsonConvert.SerializeObject(supplierData)}");
                
                // 调用API
                bool success = await PostSupplierData(supplierData);
                
                if (success)
                {
                    MessageBox.Show("供应商信息添加成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ClearForm();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加供应商时发生异常: {ex.Message}");
                MessageBox.Show($"添加供应商失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 重置供应商按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DelSup_Click(object sender, EventArgs e)
        {
            try
            {
                Console.WriteLine("重置按钮被点击");
                ClearForm();
                MessageBox.Show("表单已重置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"重置表单时发生异常: {ex.Message}");
                MessageBox.Show($"重置表单失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 调用后端API添加供应商
        /// </summary>
        /// <param name="supplierData">供应商数据</param>
        /// <returns>是否成功</returns>
        private async Task<bool> PostSupplierData(AddSupSot supplierData)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 序列化数据
                    string jsonData = JsonConvert.SerializeObject(supplierData);
                    Console.WriteLine($"发送到API的JSON数据: {jsonData}");
                    
                    // 创建HTTP内容
                    var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                    
                    // 发送POST请求
                    Console.WriteLine("正在调用API: http://10.223.8.2:4090/api/SupplierPost/PostQuery");
                    HttpResponseMessage response = await client.PostAsync("http://10.223.8.2:4090/api/SupplierPost/PostQuery", content);
                    
                    Console.WriteLine($"API响应状态码: {response.StatusCode}");
                    
                    // 读取响应内容
                    string responseContent = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"API响应内容: {responseContent}");
                    
                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("API调用成功");
                        return true;
                    }
                    else
                    {
                        Console.WriteLine($"API调用失败，状态码: {response.StatusCode}");
                        MessageBox.Show($"API调用失败，状态码: {response.StatusCode}\n响应内容: {responseContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"调用API时发生异常: {ex.Message}");
                MessageBox.Show($"调用API失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        
        /// <summary>
        /// 清空表单
        /// </summary>
        private void ClearForm()
        {
            try
            {
                // 清空所有输入控件
                if (txtsupCode != null) txtsupCode.Text = "";
                if (txtsupName != null) txtsupName.Text = "";
                
                if (txtsupPhoneName != null) txtsupPhoneName.Text = "";
                if (txtsupPhone != null) txtsupPhone.Text = "";
                if (txtsupRemark != null) txtsupRemark.Text = "";
                
                Console.WriteLine("表单已清空");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"清空表单时发生异常: {ex.Message}");
            }
        }
    }
}
